package com.itbaizhan.openhis.controller;

import com.itbaizhan.openhis.dto.UserDto;
import com.itbaizhan.openhis.service.UserService;
import com.itbaizhan.openhis.utils.ShiroSecurityUtils;
import com.itbaizhan.openhis.vo.AjaxResult;
import com.itbaizhan.openhis.vo.DataGridView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("system/user")
@Slf4j
public class UserController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 分页查询用户列表
	 *
	 * @param userDto
	 * @return
	 */
	@GetMapping("listUserForPage")
	public AjaxResult listUserForPage(UserDto userDto) {
		log.info("分页查询用户列表,{}", userDto);
		DataGridView dataGridView = userService.listUserForPage(userDto);
		return AjaxResult.success("查询成功", dataGridView.getData(), dataGridView.getTotal());
	}
	
	/**
	 * 添加用户
	 *
	 * @param userDto
	 * @return
	 */
	@PostMapping("addUser")
	public AjaxResult addUser(@Validated UserDto userDto) {
		log.info("添加用户,{}", userDto);
		userDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
		return AjaxResult.toAjax(userService.addUser(userDto));
	}
	
	/**
	 * 修改用户
	 *
	 * @param userDto
	 * @return
	 */
	@PutMapping("updateUser")
	public AjaxResult updateUser(@Validated UserDto userDto) {
		log.info("修改用户,{}", userDto);
		userDto.setSimpleUser(ShiroSecurityUtils.getCurrentSimpleUser());
		return AjaxResult.toAjax(userService.updateUser(userDto));
	}
	
	/**
	 * 批量删除用户
	 *
	 * @param userIds
	 * @return
	 */
	@DeleteMapping("deleteUserByIds/{userIds}")
	public AjaxResult deleteUserByIds(@PathVariable @Validated
									  @NotEmpty(message = "用户ID不能为空") Long[] userIds) {
		log.info("批量删除用户,{}", userIds);
		return AjaxResult.toAjax(userService.deleteUserByIds(userIds));
	}
	
	/**
	 * 重置密码
	 *
	 * @param userIds
	 * @return
	 */
	@PostMapping("resetPwd/{userIds}")
	public AjaxResult resetPwd(@PathVariable Long[] userIds) {
		log.info("重置密码,{}", userIds);
		if (userIds.length > 0) {
			userService.resetPwd(userIds);
			return AjaxResult.success("重置成功");
		}
		return AjaxResult.fail("重置失败,请选择用户id");
	}
	
	/**
	 * 查询用户信息
	 * @param userId
	 * @return
	 */
	@GetMapping("getUserById/{userId}")
	public AjaxResult getUserById(@PathVariable @Validated
									  @NotNull(message = "角色ID不能为空") Long userId){
		return AjaxResult.success(userService.getUserById(userId));
	}
	
}
